package com.wenshi.web.netty.codec;


import com.wenshi.common.core.domain.ModbusFrame;
import com.wenshi.common.utils.ByteBufUtils;
import com.wenshi.common.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class ModbusDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
        log.info("收到的数据长度:{}", buf.readableBytes());
//        ByteBuf copyByteBuf = buf.copy();
//        int copyByteBufLength = copyByteBuf.readableBytes();
//        byte[] bytes3 = ByteBufUtils.parseByteCount(copyByteBuf, copyByteBufLength);
//        String hexString = bytesToHexString(bytes3);
//        log.info("收到的报文的报文:{}", hexString);
        if (buf.readableBytes() <7) {
            return; // 不足以形成有效帧
        }
//        int transactionId = buf.readUnsignedShort();
//        int protocolId = buf.readUnsignedShort();
//        int length = buf.readUnsignedShort();
//
//        int unitId = buf.readUnsignedByte();
//        byte functionCode = buf.readByte();
//
//        ByteBuf data = buf.copy(); // 剩余的全部为数据
        byte[] bytes = ByteBufUtils.parseTwo(buf);
        String contentStr = ByteUtils.byteArrayToHexStr(bytes);
        Integer transactionId = Integer.parseInt(contentStr, 16);

        byte[] bytes1 = ByteBufUtils.parseTwo(buf);
        String contentStr1 = ByteUtils.byteArrayToHexStr(bytes1);
        Integer protocolId = Integer.parseInt(contentStr1, 16);

        byte[] bytes2 = ByteBufUtils.parseTwo(buf);
        String contentStr2 = ByteUtils.byteArrayToHexStr(bytes2);
        Integer length = Integer.parseInt(contentStr2, 16);

        byte[] headbytes = ByteBufUtils.parseOne(buf);
        String contentStr3 = ByteUtils.byteArrayToHexStr(headbytes);
        Integer unitId = Integer.parseInt(contentStr3, 16);
        log.info("transactionId:{},protocolId:{},unitId:{},length:{}",transactionId,protocolId,unitId,length);

        byte functionCode = buf.readByte();
        byte[] data1 = ByteBufUtils.parseByteCount(buf, length - 2);
        ByteBuf data = Unpooled.buffer();
        data.writeBytes(data1);
        ModbusFrame modbusFrame = new ModbusFrame(transactionId, protocolId, length, unitId, functionCode,data);
        out.add(modbusFrame);
    }
}
